import { TokenTypes } from './tokenizer.type'

export const parser = (tokens) => {
  let current = 0
  interface Ast {
    type: string
    body?: any
    name?: string
    params?: any
  }
  let ast: Ast = {
    type: 'Program',
    body: [],
  }
  function walk() {
    let token = tokens[current]
    if (token.type === TokenTypes.LeftParen) {
      token = tokens[++current]
      let node: Ast = {
        type: 'CallExpression',
        name: token.value,
        params: [],
      }
      token = tokens[++current]
      while (
        token &&
        token.type !== TokenTypes.RightParen &&
        current < tokens.length
      ) {
        node.params.push(walk())
        token = tokens[current]
        console.log(999, token)
      }
      current++
      return node
    }
    if (token.type === TokenTypes.Number) {
      current++
      return {
        type: 'NumberLiteral',
        value: token.value,
      }
    }
    if (token.type === TokenTypes.String) {
      current++
      return {
        type: 'StringLiteral',
        value: token.value,
      }
    }
    throw new TypeError(token.type)
  }
  while (current < tokens.length) {
    ast.body.push(walk())
  }
  console.log('输出 ast', ast)
  return ast
}
